package io.renren.modules.generator.controller;

import com.baomidou.mybatisplus.mapper.Condition;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.app.enums.OutOrderStatusEnum;
import io.renren.modules.app.request.outorder.SubmitOutOrderItemReq;
import io.renren.modules.app.request.outorder.SubmitOutOrderReq;
import io.renren.modules.generator.entity.*;
import io.renren.modules.generator.service.*;
import io.renren.modules.generator.vo.OtOrderListVo;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 入库单
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-12-13 23:13:40
 */
@RestController
@RequestMapping("generator/outorder")
public class OutOrderController {

    @Autowired
    private OutOrderService outOrderService;

    @Autowired
    StockService stockService;
    @Autowired
    PositionService positionService;

    @Autowired
    OutOrderItemService outOrderItemService;

    @Autowired
    KucunService kucunService;

    @PostMapping("submitOutOrder")
    @RequiresPermissions("generator:outorder:submitorder")
    public R submitOutOrder(@RequestBody SubmitOutOrderReq req) {
        if (req.getOrderItems().stream().filter(k -> k.getQuantity() == 0).findFirst().isPresent()) {
            return R.error("出库商品数量不能为0");
        }
        SysUserEntity user = ShiroUtils.getUserEntity();

        OutOrderEntity order = new OutOrderEntity();
        order.setOrderNo(req.getOrderNo());
        order.setStatus(OutOrderStatusEnum.初始化.getValue());
        order.setCreateTime(new Date());
        order.setCreateUser(user.getUsername());
        //先扣减库存，不足时直接返回
        List<KucunEntity> deItems = new ArrayList<>();
        req.getOrderItems().stream().forEach(y->{
            KucunEntity den = new KucunEntity();
            den.setBatchNo(y.getBatchNo());
            den.setItemGuid(y.getGuid());
            den.setVirAmount(y.getQuantity());
            deItems.add(den);
        });
        try {
            if (kucunService.decreaceVirKucun(deItems) == 0) {
                return R.error("库存不足");
            }
        } catch (Exception e) {
            return R.error("库存不足，可能存在多拣货订单");
        }
        if (outOrderService.insert(order)) {
            List<OutOrderItemEntity> orderItems = new ArrayList<>();
            List<SubmitOutOrderItemReq> reqItems = req.getOrderItems();
            reqItems.stream().forEach(x -> {
                OutOrderItemEntity vo = new OutOrderItemEntity();
                BeanUtils.copyProperties(x, vo);
                vo.setItemGuid(x.getGuid());
                vo.setBatchNo(x.getBatchNo());
                vo.setQuantity(x.getQuantity());
                vo.setOrderNo(req.getOrderNo());
                vo.setProportion(100.0);
                PositionEntity pos = positionService.selectOne(Condition.create().eq("ps_code", x.getPsCode()));
                vo.setPsCode(x.getPsCode());
                vo.setAreaCode(pos == null ? "" : pos.getAreaCode());
                orderItems.add(vo);
            });
            if (orderItems.size() > 0) {
                outOrderItemService.insertBatch(orderItems);
            }
        }
        return R.ok();
    }

    /**
     * 单号生成
     */
//    @RequestMapping("/getOrderNo")
//    @RequiresPermissions("generator:outorder:getOrderNo")
//    public R getOrderNo() {
//        StringBuilder prefix = new StringBuilder();
//        prefix.append("O");
//        prefix.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmssSSS")));
//        return R.ok().put("orderNo", prefix.toString());
//    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:outorder:list")
    public R list(@RequestParam Map<String, Object> params) {

        if (params.containsKey("key") && StringUtils.isNotBlank(params.get("key").toString())) {
            params.put("orderNo", params.get("key"));
        }
        List<OtOrderListVo> response = new ArrayList<>();
        PageUtils page = outOrderService.queryPage(params);
        List<OutOrderEntity> datas = (List<OutOrderEntity>) page.getList();
        datas.stream().forEach(x -> {
            OtOrderListVo vo = new OtOrderListVo();
            if (x.getFinishTime().getTime() < 100000) {
                x.setFinishTime(null);
            }
            BeanUtils.copyProperties(x, vo);
            response.add(vo);
        });
        page.setList(response);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("generator:outorder:info")
    public R info(@PathVariable("id") Long id) {
        OutOrderEntity outOrder = outOrderService.selectById(id);

        return R.ok().put("outOrder", outOrder);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("generator:outorder:save")
    public R save(@RequestBody OutOrderEntity outOrder) {
        outOrderService.insert(outOrder);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("generator:outorder:update")
    public R update(@RequestBody OutOrderEntity outOrder) {
        outOrderService.updateById(outOrder);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:outorder:delete")
    public R delete(@RequestBody Long[] ids) {
        outOrderService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

}
